package com.cloudinnov.logic.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cloudinnov.dao.AuthDeptUserDao;
import com.cloudinnov.dao.AuthRoleUserDao;
import com.cloudinnov.dao.AuthUserDao;
import com.cloudinnov.logic.AuthUserLogic;
import com.cloudinnov.model.AuthDeptUser;
import com.cloudinnov.model.AuthResource;
import com.cloudinnov.model.AuthRoleUser;
import com.cloudinnov.model.AuthUsers;
import com.cloudinnov.utils.CodeUtil;
import com.cloudinnov.utils.CommonUtils;
import com.cloudinnov.utils.PropertiesUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @author chengning
 * @date 2016年2月17日下午7:02:09
 * @email ningcheng@cloudinnov.com
 * @remark
 * @version
 */
@Service
public class AuthUserLogicImpl extends BaseLogicImpl<AuthUsers> implements AuthUserLogic {

	private static final Logger logger = LoggerFactory.getLogger(AuthUserLogicImpl.class);
	
	
	private int digit = 5;
	
	private final static String USER_EXIST_KEY = "user_exist:";
	private final static String USER_PHONE = "phone";
	private final static String USER_LOGINNAME = "loginname";
	
	// 验证码错误
	public static final int LOGIN_ERROR_VERIFYCODE = 10005;

	// 验证码错误超时
	public static final int LOGIN_ERROR_VERIFYCODE_TIMEOUT = 10006;
	
	@Autowired
	private AuthUserDao authUserDao;
	
	@Autowired
	private AuthRoleUserDao authRoleUserDao;
	
	@Autowired
	private AuthDeptUserDao authDeptUserDao;
	
	@Autowired
	private JedisPool jedisPool;

	@Override
	public AuthUsers login(AuthUsers user) {
		if (CommonUtils.isNotEmpty(user.getLoginName()) || CommonUtils.isNotEmpty(user.getLoginPassword())) {
			AuthUsers loginUser = authUserDao.selectByNamePwd(user);
			if (loginUser != null && loginUser.getLoginPassword() != null
					&& loginUser.getLoginPassword().equals(CommonUtils.MD5(user.getLoginPassword()))) {
				loginUser.setLoginPassword("");
				return loginUser;
			} else {
				return null;
			}
		}
		return null;
	}
	

	@Override
	public int save(AuthUsers user) {
		if (user.getLoginPassword() == null) {
			return 0;
		}
		user.setLoginPassword(CommonUtils.MD5(user.getLoginPassword()));
		user.setCode(CodeUtil.userCode(digit));
		int returnCode = authUserDao.insert(user);
		if (returnCode == CommonUtils.SUCCESS_NUM) {
			returnCode = authUserDao.insertInfo(user);
			if(CommonUtils.isNotEmpty(user.getRoleCode())){
				String[] roleCodes = user.getRoleCode().split(CommonUtils.SPLIT_COMMA);
				for(String roleCode : roleCodes){
					user.setRoleCode(roleCode);
					returnCode = authUserDao.insertUserRole(user);
				}
			}
			if(CommonUtils.isNotEmpty(user.getDeptCode())){
				String[] deptCodes = user.getDeptCode().split(CommonUtils.SPLIT_COMMA);
				AuthDeptUser deptUser = null;
				for(String deptCode : deptCodes){
					deptUser = new AuthDeptUser();
					deptUser.setCompanyCode(user.getCompanyCode());
					deptUser.setDeptCode(deptCode);
					deptUser.setUserCode(user.getCode());
					returnCode = authDeptUserDao.insert(deptUser);
				}
			}
		} else {
			returnCode = 0;
		}
		return returnCode;
	}

	@Override
	public int update(AuthUsers user) {
		if (user.getLoginPassword() != null) {
			user.setLoginPassword(CommonUtils.MD5(user.getLoginPassword()));
		}
		int returnCode = authUserDao.updateByCondition(user);
		if (returnCode == CommonUtils.SUCCESS_NUM) {
			returnCode = authUserDao.updateInfoByCondition(user);
			if(CommonUtils.isNotEmpty(user.getRoleCode())){
				AuthRoleUser roleUser = new AuthRoleUser();
				roleUser.setUserCode(user.getCode());
				authRoleUserDao.deleteByCondition(roleUser);
				String[] roleCodes = user.getRoleCode().split(CommonUtils.SPLIT_COMMA);
				for(String roleCode : roleCodes){
					user.setRoleCode(roleCode);
					returnCode = authUserDao.insertUserRole(user);
				}
			}
			if(CommonUtils.isNotEmpty(user.getDeptCode())){
				AuthDeptUser deptUser = new AuthDeptUser();
				deptUser.setUserCode(user.getCode());
				authDeptUserDao.deleteByCondition(deptUser);
				String[] deptCodes = user.getDeptCode().split(CommonUtils.SPLIT_COMMA);
				for(String deptCode : deptCodes){
					deptUser = new AuthDeptUser();
					deptUser.setCompanyCode(user.getCompanyCode());
					deptUser.setDeptCode(deptCode);
					deptUser.setUserCode(user.getCode());
					returnCode = authDeptUserDao.insert(deptUser);
				}
			}
		} else {
			returnCode = 0;
		}
		return returnCode;
	}

	
	@Override
	public int delete(AuthUsers entity) {
		AuthUsers user = authUserDao.selectEntityByCondition(entity);
		int returnCode = super.delete(entity);
		if(returnCode == CommonUtils.SUCCESS_NUM){
			Jedis redisClient = null;
			try {
				redisClient = jedisPool.getResource();
				redisClient.select(Integer.parseInt(PropertiesUtils.findPropertiesKey("redis.db.login")));	
				redisClient.del(USER_EXIST_KEY+ user.getLoginName());
			}catch(Exception ex){
				logger.error("deleteUser Exception \r\n" , ex);
			}
		}
		return returnCode;
	}


	@Override
	public List<AuthResource> selectResourceByUserCodeAndCompanyCode(String userCode, String companyCode) {
		Map<Object, Object> codes = new HashMap<Object, Object>();
		codes.put("code", userCode);
		codes.put("companyCode", companyCode);
		return authUserDao.selectResourcesByCode(codes);
	}

	@Override
	public Page<AuthUsers> selectOemUserList(int index, int size, Map<String, Object> map) {
		PageHelper.startPage(index, size);
		return (Page<AuthUsers>) authUserDao.selectOemUserList(map);
	}

	@Override
	public List<AuthUsers> selectOemUserList(Map<String, Object> map) {
		if(map.get("index")!=null){
			PageHelper.startPage((Integer) map.get("index"), (Integer)map.get("size"));
			return authUserDao.selectOemUserList(map);
		}
		return authUserDao.selectOemUserList(map);
		
	}

	@Override
	public List<AuthUsers> selectCustomerUserList(Map<String, Object> map) {
		return authUserDao.selectCustomerUserList(map);
	}

	@Override
	public int updateLanguage(AuthUsers user) {
		int returnCode = authUserDao.insertInfo(user);
		if (returnCode != CommonUtils.SUCCESS_NUM) {
			returnCode = 0;
		}
		return returnCode;
	}

	@Override
	public int changePassword(AuthUsers user) {
		if (user.getNewPassword() == null) {
			return 0;
		}
		user.setLoginPassword(CommonUtils.MD5(user.getNewPassword()));
		return authUserDao.updateByCondition(user);
	}

	@Override
	public int updateUserInfo(AuthUsers user) {
		int returnCode = authUserDao.updateUserInfo(user);
		if(returnCode>=CommonUtils.SUCCESS_NUM){
				authUserDao.updateInfoByCondition(user);
		}
		return returnCode;
	}


	@Override
	public int checkLoginNameOrPhone(AuthUsers user) {
		//穿透去查询redis
		Jedis redisClient = null;
		int isExist = 0;
		try {
			redisClient = jedisPool.getResource();
			redisClient.select(Integer.parseInt(PropertiesUtils.findPropertiesKey("redis.db.login")));
			String data = redisClient.hget(USER_EXIST_KEY + user.getLoginName(), USER_LOGINNAME);
			data = redisClient.hget(USER_EXIST_KEY + user.getPhone(), USER_PHONE);
			if(data!=null){
				isExist = 1;
			}else{
				user = authUserDao.selectByNameOrPhone(user);
				if(user!=null){
					redisClient.hset(USER_EXIST_KEY+ user.getLoginName(), USER_LOGINNAME, user.getLoginName());
					redisClient.hset(USER_EXIST_KEY+ user.getLoginName(), USER_PHONE, user.getPhone());
					isExist = 1;
				}
			}
		}catch(Exception e){
			isExist = 1;
			logger.error("checkLoginNameOrPhone Exception \r\n {}" , e);
		}
		return isExist;
	}
	
	@Override
	public int androidLoginCheck(AuthUsers user) {
		
		Jedis redisClient = null;
		int returnCode = 0;
		try {	
			if(user.getDeviceId() != null){ //标识安卓登录
				redisClient = jedisPool.getResource();
				redisClient.select(Integer.parseInt(PropertiesUtils.findPropertiesKey("redis.db.login")));
				redisClient.set("app:login:"+user.getLoginName(), user.getDeviceId()+ ":" +user.getToken());
				redisClient.set("app:login:"+user.getToken(), user.getDeviceId()+ ":" +user.getToken());
			}
		} catch(Exception e){
			logger.error("androidLoginCheck Exception \r\n" , e);
		}finally{
			jedisPool.returnResource(redisClient);
		}	
		return returnCode;
	}

	@Override
	public int checkLoginPassword(AuthUsers user) {
		user.setLoginPassword(CommonUtils.MD5(user.getLoginPassword()));
		int returnCode = authUserDao.selectByCondition(user);
		if(returnCode == CommonUtils.SUCCESS_NUM){
			return CommonUtils.SUCCESS_NUM;
		}
		return 0;
	}
	
	@Override
	public int checkVerifyCode(String type, AuthUsers user) {
		Jedis redisClient = null;
		try {
			redisClient = jedisPool.getResource();
			redisClient.select(Integer.parseInt(PropertiesUtils.findPropertiesKey("redis.db.login")));
			String verifyCode = redisClient.get(type +":verify:code:" + user.getDeviceId());
			if (verifyCode == null) {// 判断验证码不区分大小写
				return LOGIN_ERROR_VERIFYCODE_TIMEOUT;
			}else if(!verifyCode.equalsIgnoreCase(user.getVerifyCode())){
				return LOGIN_ERROR_VERIFYCODE;
			}			
		}catch(Exception e){
			logger.error("checkVerifyCode:\r", e);
		}finally {
			jedisPool.returnResource(redisClient);
		}
		return CommonUtils.SUCCESS_NUM;
	}
	
	@Override
	public AuthUsers selectAreaAndPhone(String phone) {
		if(phone.trim().split("-").length > 1){
			phone = phone.trim().split("-")[1];
		}
		List<AuthUsers> users = authUserDao.selectAreaAndPhone(phone);
		if(users!=null && users.size()>0){
			AuthUsers user = users.get(0);//默认取第一条数据
			//user.setPhone(user.getPhone().trim().split("-")[0] + user.getPhone().trim().split("-")[1]);//拼接为区号加手机号，去除-
			if(user.getPhone()!=null && user.getPhone().trim().split("-").length>1){
				user.setPhone(user.getPhone().trim().split("-")[1]);//拼接为区号加手机号，去除-
			}else if(user.getPhone().trim().split("-").length == 1){
				user.setPhone(user.getPhone().trim().split("-")[0]);//拼接为区号加手机号，去除-
			}
			
			return user;
		}
		return null;
	}
	
	@Override
	public int resetPassword(AuthUsers user) {
		user.setLoginPassword(CommonUtils.MD5(user.getLoginPassword()));
		return authUserDao.resetPassword(user);
	}
}
